package com.manager.modelserver.redis;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtils {
    private volatile static JedisPool jedisPool;
    public static Jedis jedis;
    public static Jedis getPoolJedis() {
        if (jedisPool == null) {
            synchronized (JedisPoolUtils.class) {
                if (jedisPool == null) {
                    jedisPool = initJedis();
                }
            }
        }

        return jedisPool.getResource();
    }


    private static JedisPool initJedis(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10);
        jedisPoolConfig.setMaxWaitMillis(5000);
        //poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, null
        JedisPool jedisPool = new JedisPool(jedisPoolConfig,"127.0.0.1",6379,2000,null,2);
        return jedisPool;
    }

    public static void main(String[] args) {
        //推荐写法
        try{
            JedisPoolUtils.jedis  = JedisPoolUtils.getPoolJedis();
            //执行
            jedis.exists("aa");
            jedis.set("aa","aaaa");
            System.out.println(JedisPoolUtils.getPoolJedis().ping());
            System.out.println(JedisPoolUtils.getPoolJedis().get("aa"));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if ( JedisPoolUtils.jedis  != null){
                JedisPoolUtils.jedis.close(); //归还连接池
            }
        }



    }
}
